<template>
  <div :id="id" :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
export default {
  props: {
    className: {
      type: String,
      default() {
        return 'chart'
      }
    },
    tabName: {
      type: String,
      default() {
        return 'cruxAuditDataTotalVo'
      }
    },
    id: {
      type: String,
      default() {
        return 'chart'
      }
    },
    width: {
      type: String,
      default() {
        return '200px'
      }
    },
    height: {
      type: String,
      default() {
        return '200px'
      }
    },
    title: {
      type: String,
      default() {
        return '报警类型分布'
      }
    },
    titleLocation: {
      type: String,
      default() {
        return 'center'
      }
    },
    legend: {
      type: Object,
      default() {
        return {
          orient: 'horizontal',
          left: 'center', // 水平位置，可选值：'left', 'center', 'right'
          bottom: 20 // 垂直位置，可选值：'top', 'middle', 'bottom'
        }
      }
    },
    options: {
      type: Array,
       default() {
        return []
      }
    },
  },
  data() {
    return {
      chart: null,
      chartOption: null
    }
  },

  watch: {
    options: {
      deep: true,
      handler(newVal, oldVal) {
        const xData = [], barData = [], lineData = []
          newVal.forEach(item => {
            const { abscissaValue, alarmCount, alarmRate, colonyAlarmCount, retailAlarmCount, travelAlarmCount, vehicleSellAlarmCount } = item
            xData.push(item.abscissaValue)
            barData.push({
              name: abscissaValue,
              value: alarmCount,
              alarmRate,
              colonyAlarmCount,
              retailAlarmCount,
              travelAlarmCount, 
              vehicleSellAlarmCount
            })
            lineData.push({value: alarmRate})
          })
        this.chartOption.series[0].data = barData
        this.chartOption.series[1].data = lineData
        this.chartOption.xAxis[0].data = xData
        this.chart.setOption(this.chartOption)
        // console.log('arr changed', xData, barData, lineData)
      }
    },
    tabName: {
      handler(newVal, oldVal) {
        this.chart.resize()
      }
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.handleResize);
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id))
      const _this = this
      const option = {
        grid: {
          left: '2%',  // 左边距为5%的百分比
          right: '2%', // 右边距为5%的百分比
          containLabel: true // 容纳标签，避免标签被裁剪
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#f2f2f2', // 背景颜色
          textStyle: {
            color: '#333' // 文本颜色
          },
          formatter: function (params) {
            const current = params[0].data
            let result = `
                  <div style="color: '#333'; font-weight: 650">${current.name}</div>
                  实际报警率：${current.alarmRate}% <br/>
                  报警总数：${current.value}台<br/>
                  ${_this.tabName === 'cruxAuditDataRetailVo' || _this.tabName === 'cruxAuditDataTotalVo'  ? `零售车辆报警数${current.retailAlarmCount}台<br/>` : ''}
                  ${_this.tabName === 'cruxAuditDataTravelVo' || _this.tabName === 'cruxAuditDataTotalVo' ? `出行车辆报警数${current.travelAlarmCount}台<br/>` : ''}
                  <br/>车辆摆卖报警数：${current.vehicleSellAlarmCount}台<br/>
                  非属地上牌报警数${current.colonyAlarmCount}台<br/>
                `
            return result;
          }
        },
    
        legend: {
            data: ['报警数', '报警率'],
            orient: 'horizontal',
            left: 'right', // 水平位置，可选值：'left', 'center', 'right'
            top: 'top' // 垂直位置，可选值：'top', 'middle', 'bottom'
        },
        xAxis: [
          {
            type: 'category',
            data: [],
            axisPointer: {
                type: 'shadow'
            },
            axisLabel: {
              interval: 0 ,
              // rotate: -90,
              formatter: function (value) {
                if (_this.horizontal) {
                  return value
                } else {
                  let text, length = 4; // 文字显示长度
                  if (value.length>length) {
                      text = value.slice(0,length) + '…'
                  } else {
                      text = value
                  }
                  return '{a|' +`${text.split("").join("\n")}` + '}' //垂直显示
                }
              },
              rich:{
                a:{
                  height:14,  //设置行高
                }
              }
            }
          }
        ],
        yAxis: [
            {
                type: 'value',
                name: '报警数：台',
            },
            {
                type: 'value',
                name: '报警率：%',
            }
        ],
        series: [
            {
              name: '报警数',
              type: 'bar',
              data: [],
              itemStyle: {
                normal: {
                  // 默认柱状图颜色
                  color: '#aaaaaa'
                },
                emphasis: {
                  // 鼠标悬浮时的柱状图颜色
                  color: '#20a8ac'
                }
              }
            },
            {
                name: '报警率',
                type: 'line',
                data: [],
                max: 100,
                min: 0,
                itemStyle: {
                  normal: {
                    color: '#97e918'
                  }
                }
            }
        ]
      }
      this.chartOption = option
      this.chart.setOption(option)
    },
    handleResize() {
      this.chart.resize()
    }
  }
}
</script>
